package com.knight.async;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

/**
 * @author knight
 */
@Component
public class QueueListener implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(QueueListener.class);
    @Autowired
    private MockQueue mockQueue;
    @Autowired
    private DeferredResultHolder deferredResultHolder;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        LOGGER.info("-----application event--------");
        new Thread(() -> {
            while (true) {
                String completeOrder = mockQueue.getCompleteOrder();
                if (StringUtils.isNotBlank(completeOrder)) {
                    LOGGER.info("--返回订单处理结果:{}--", completeOrder);
                    DeferredResult<String> deferredResult = deferredResultHolder.getMap().get(completeOrder);
                    deferredResult.setResult("place order[" + completeOrder + "] success");
                    mockQueue.setCompleteOrder(null);
                } else {
                    try {
                        Thread.sleep(200L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
